<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="送货单号" prop="deliveryId">
        <el-input
          v-model="queryParams.deliveryId"
          placeholder="请输入送货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购订单号" prop="poId">
        <el-input
          v-model="queryParams.poId"
          placeholder="请输入采购订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>




      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:delivery:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:delivery:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchase:delivery:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchase:delivery:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deliveryList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="发货状态" align="center" prop="deliveryStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.deliveryStatus === 0" type="warning">待发货</el-tag>
          <el-tag v-else type="success">已发货</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="送货单号" align="center" prop="deliveryId" />
      <el-table-column label="采购订单号" align="center" prop="poId" />
      <el-table-column label="送货日期" align="center" prop="deliveryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="总箱数" align="center" prop="totalBoxes" />
      <el-table-column label="本次送货数量" align="center" prop="totalQuantity" />
      <el-table-column label="创建人" align="center" prop="createdPerson" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['purchase:delivery:confirm']"
            v-if="scope.row.deliveryStatus === 0"
          >确认发货</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="handlePrint(scope.row)"
            v-hasPermi="['purchase:delivery:query']"
          >打印</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['purchase:delivery:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:delivery:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchase:delivery:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改发货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="采购订单号" prop="poId">
<!--          <el-input v-model="form.poId" style="width: 350px" placeholder="请选择采购订单号" readonly>-->
            <el-button type="primary"  @click="handleSelectPurchaseOrder">请选择采购订单号</el-button>
<!--          </el-input>-->
        </el-form-item>
        <el-form-item label="选择箱码">
          <el-button type="primary" @click="handleSelectBoxCodes"  :disabled="!form.poId">
            选择箱码
          </el-button>
          <span style="margin-left: 10px; color: #666;">已选择 {{ selectedBoxCodes.length }} 箱</span>
        </el-form-item>
        <el-form-item label="送货日期" prop="deliveryDate">
          <el-date-picker
            v-model="form.deliveryDate"
            type="date"
            placeholder="选择送货日期"
            value-format="yyyy-MM-dd"
            style="width: 100%;"
          />
        </el-form-item>




        <!-- 送货清单区域 -->
        <el-divider content-position="center">送货清单</el-divider>
          <el-table :data="deliveryItems" border>
            <el-table-column prop="poId" label="采购订单号" />
            <el-table-column prop="itemId" label="存货编码" />
            <el-table-column prop="itemName" label="存货名称" />
            <el-table-column prop="poNum" label="订单数量" />
            <el-table-column prop="codeNum" label="未送料数量" />
            <el-table-column prop="currentDeliveryQuantity" label="本次送货数量" />
            <el-table-column prop="boxCount" label="箱数" />
            <el-table-column prop="remark" label="备注">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" placeholder="请输入备注" />
              </template>
            </el-table-column>
          </el-table>

        <!-- 箱码列表区域 -->
        <el-divider content-position="center">箱码列表</el-divider>
          <el-table :data="selectedBoxCodes" border>
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column prop="boxId" label="箱码" />
            <el-table-column prop="itemName" label="存货名称" />
            <el-table-column prop="spec" label="规格型号" />
            <el-table-column prop="batch" label="批次号" />
            <el-table-column prop="uom" label="计量单位" />
            <el-table-column prop="spec" label="规格型号" />
            <el-table-column prop="boxNum" label="箱码数量" />
            <el-table-column prop="productionDate" label="生产日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleRemoveBoxCode(scope.$index)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




    <!-- 选择采购订单对话框 -->
    <el-dialog title="选择采购订单" :visible.sync="purchaseOrderDialogVisible" width="80%" append-to-body>
      <purchase-order-select @select="handlePurchaseOrderSelect" />
    </el-dialog>

    <!-- 选择箱码对话框 -->
    <el-dialog title="选择箱码" :visible.sync="boxCodeDialogVisible" width="90%" append-to-body>
      <box-code-select
        :po-id="form.poId"
        @select="handleBoxCodeSelect"
        v-if="boxCodeDialogVisible"
      />
    </el-dialog>



    <!-- 查看详情对话框 -->
    <el-dialog title="发货单详情" :visible.sync="viewOpen" width="1200px" append-to-body>
      <el-form :column="3" border v-if="currentDelivery">
        <el-form-item label="送货单号">{{ currentDelivery.deliveryId }}</el-form-item>
        <el-form-item label="采购订单号">{{ currentDelivery.poId }}</el-form-item>
        <el-form-item label="送货日期">{{ parseTime(currentDelivery.deliveryDate, '{y}-{m}-{d}') }}</el-form-item>
        <el-form-item label="发货状态">
          <el-tag v-if="currentDelivery.deliveryStatus === 0" type="warning">待发货</el-tag>
          <el-tag v-else type="success">已发货</el-tag>
        </el-form-item>
        <el-form-item label="总箱数">{{ currentDelivery.totalBoxes }}</el-form-item>
        <el-form-item label="总数量">{{ currentDelivery.totalQuantity }}</el-form-item>
        <el-form-item label="创建人">{{ currentDelivery.createdPerson }}</el-form-item>
        <el-form-item label="创建时间">{{ parseTime(currentDelivery.createdAt, '{y}-{m}-{d}') }}</el-form-item>
        <el-form-item label="备注">{{ currentDelivery.remark }}</el-form-item>
        <!-- 送货清单 -->
        <el-card header="送货清单" style="margin-top: 20px;">
         <el-table :data="currentDelivery.deliveryItems" border>
        <el-table-column prop="poId" label="采购订单号" />
        <el-table-column prop="itemId" label="存货编码" />
        <el-table-column prop="itemName" label="存货名称" />
        <el-table-column prop="spec" label="规格型号" />
        <el-table-column prop="uom" label="计量单位" />
        <el-table-column prop="poNum" label="订单数量" />
        <el-table-column prop="codeNum" label="未送料数量" />
        <el-table-column prop="currentDeliveryQuantity" label="送货数量" />
        <el-table-column prop="boxCount" label="箱数" />
        </el-table>
        </el-card>
        <!-- 箱码列表 -->
        <el-card header="箱码列表" style="margin-top: 20px;">
          <el-table :data="currentDelivery.boxCodes" border>
            <el-table-column prop="boxId" label="箱码" />
            <el-table-column prop="itemName" label="存货名称" />
            <el-table-column prop="spec" label="规格型号" />
            <el-table-column prop="batch" label="批次号" />
            <el-table-column prop="boxNum" label="箱码数量" />
            <el-table-column prop="productionDate" label="生产日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="binId" label="库位编号" />
          </el-table>
        </el-card>
      </el-form>
    </el-dialog>

    <!-- 打印内容区域（隐藏，只在打印时显示） -->
    <div id="printContent" style="display: none;">
      <div class="print-container" style="padding: 20px; font-family: 'Microsoft YaHei';">
        <div class="print-header" style="text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px;">
          <h1 style="margin: 0; font-size: 28px;">送货单</h1>
        </div>

        <!-- 基本信息 -->
        <div class="print-info" style="margin-bottom: 20px;">
          <table style="width: 100%; border-collapse: collapse; font-size: 14px;">
            <tr>
              <td style="padding: 5px 0; width: 25%;"><strong>送货单号:</strong> <span id="printDeliveryId"></span></td>
              <td style="padding: 5px 0; width: 25%;"><strong>采购订单号:</strong> <span id="printPoId"></span></td>
              <td style="padding: 5px 0; width: 25%;"><strong>送货日期:</strong> <span id="printDeliveryDate"></span></td>
              <td style="padding: 5px 0; width: 25%;"><strong>总箱数:</strong> <span id="printTotalBoxes"></span></td>
            </tr>
          </table>
        </div>

        <!-- 送货清单表格 -->
        <div class="print-table" style="margin-bottom: 20px;">
          <!-- 修改表格的列宽，确保所有列宽总和为100% -->
          <table style="width: 100%; border-collapse: collapse; border: 1px solid #000; font-size: 12px; table-layout: fixed; transform: rotate(0deg);">
            <thead>
            <tr style="background-color: #f5f5f5;">
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 8%;">序号</th>
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 12%;">存货编码</th>
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 18%;">存货名称</th>
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 18%;">规格型号</th>
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 10%;">计量单位</th>
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 14%;">本次送货数量</th>
              <th style="border: 1px solid #000; padding: 8px; text-align: center; width: 20%;">备注</th>
            </tr>
            </thead>
            <tbody id="printTableBody">
            <!-- 表格内容 -->
            </tbody>
          </table>
        </div>

        <!-- 二维码区域 -->
        <div class="print-qrcode" style="display: flex; justify-content: space-between; align-items: flex-start; margin-top: 30px;">
          <div style="flex: 1;">
            <div style="margin-bottom: 10px;"><strong>签收信息:</strong></div>
            <div style="border: 1px solid #000; height: 140px; padding: 10px;">
              <p>收货单位：___________________</p>
              <p>收货人：___________________</p>
              <p>签收日期：___________________</p>
            </div>
          </div>
          <div style="text-align: center; margin-left: 20px;">
            <div id="qrcode" style="margin-bottom: 10px;"></div>
            <div style="font-size: 12px;">扫描二维码查看详细信息</div>
          </div>
        </div>

        <div class="print-footer" style="text-align: center; margin-top: 30px; font-size: 12px; color: #666;">
          <p>打印时间: <span id="printTime"></span></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listDelivery, getDelivery, delDelivery, addDelivery, updateDelivery,confirmDelivery } from "@/api/purchase/delivery"
import PurchaseOrderSelect from '../../../../src/components/PurchaseOrderSelect'
import BoxCodeSelect from '../../../../src/components/BoxCodeSelect'
import {getDeliveryVO, listDeliveryVO} from "../../../api/purchase/delivery";
import QRCode from 'qrcode'
export default {
  name: "Delivery",
  components: {
    PurchaseOrderSelect,
    BoxCodeSelect
  },
  data() {
    return {
      // 选中的箱码
      deliveryItems:null,
      selectedBoxCodes: [],
      // 当前查看的发货单
      currentDelivery: null,
      viewOpen: false,
      purchaseOrderDialogVisible: false,
      boxCodeDialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedDeliveryDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发货单表格数据
      deliveryList: [],
      // 发货单明细表格数据
      deliveryDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deliveryId: null,
        poId: null,
        deliveryDate: null,
      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        deliveryId: [
          { required: true, message: "送货单号不能为空", trigger: "blur" }
        ],
        poId: [
          { required: true, message: "采购订单号不能为空", trigger: "blur" }
        ],
        deliveryDate: [
          { required: true, message: "送货日期不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
// 打印操作
    handlePrint(row) {
      this.loading = true;
      getDeliveryVO(row.id).then(response => {
        const deliveryData = response.data;
        this.doPrint(deliveryData);
        this.loading = false;
      }).catch(error => {
        console.error('获取发货单详情失败:', error);
        this.loading = false;
        this.$modal.msgError("获取发货单详情失败");
      });
    },
      // 执行打印
      doPrint(deliveryData)
      {
        // 显示打印内容
        const printContent = document.getElementById('printContent');
        printContent.style.display = 'block';
        // 填充基本信息
        document.getElementById('printDeliveryId').textContent = deliveryData.deliveryId || '';
        document.getElementById('printPoId').textContent = deliveryData.poId || '';
        document.getElementById('printDeliveryDate').textContent = this.parseTime(deliveryData.deliveryDate, '{y}-{m}-{d}');
        document.getElementById('printTotalBoxes').textContent = deliveryData.totalBoxes || 0;
        document.getElementById('printTime').textContent = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');

        // 填充表格内容
        const tableBody = document.getElementById('printTableBody');
        tableBody.innerHTML = '';

        if (deliveryData.deliveryItems && deliveryData.deliveryItems.length > 0) {
          deliveryData.deliveryItems.forEach((item, index) => {
            const row = document.createElement('tr');
            // 在 doPrint 方法中修改表格行生成代码
            row.innerHTML = `
  <td style="border: 1px solid #000; padding: 8px; text-align: center; width: 8%;">${index + 1}</td>
  <td style="border: 1px solid #000; padding: 8px; text-align: left; width: 12%;">${item.itemId || ''}</td>
  <td style="border: 1px solid #000; padding: 8px; text-align: left; width: 20%;">${item.itemName || ''}</td>
  <td style="border: 1px solid #000; padding: 8px; text-align: left; width: 20%;">${item.spec || ''}</td>
  <td style="border: 1px solid #000; padding: 8px; text-align: center; width: 10%;">${item.uom || ''}</td>
  <td style="border: 1px solid #000; padding: 8px; text-align: right; width: 15%;">${item.currentDeliveryQuantity || 0}</td>
  <td style="border: 1px solid #000; padding: 8px; text-align: left; width: 15%;">${item.remark || ''}</td>
`;
            tableBody.appendChild(row);
          });
        }

        // 生成二维码
        this.generateQRCode(deliveryData);


        // 执行打印
        setTimeout(() => {
          window.print();

          // 打印完成后隐藏打印内容
          setTimeout(() => {
            printContent.style.display = 'none';
          }, 500);
        }, 500);
    },

        // 生成二维码
        generateQRCode(deliveryData){
          try {
            // 准备二维码数据
            const qrData = {
              deliveryId: deliveryData.deliveryId,
              poId: deliveryData.poId,
              deliveryDate: this.parseTime(deliveryData.deliveryDate, '{y}-{m}-{d}'),
              totalBoxes: deliveryData.totalBoxes,
              totalQuantity: deliveryData.totalQuantity,
              items: deliveryData.deliveryItems ? deliveryData.deliveryItems.map(item => ({
                itemId: item.itemId,
                itemName: item.itemName,
                quantity: item.currentDeliveryQuantity
              })) : []
            };

            const qrCodeString = JSON.stringify(qrData);

            const qrcodeElement = document.getElementById('qrcode');
            qrcodeElement.innerHTML = '';

            QRCode.toCanvas(qrCodeString, {
              width: 120,
              height: 120,
              margin: 1
            }, function (err, canvas) {
              if (err) {
                console.error('生成二维码失败:', err);
                qrcodeElement.innerHTML = '<div style="width: 120px; height: 120px; border: 1px solid #ccc; display: flex; align-items: center; justify-content: center; font-size: 12px;">二维码生成失败</div>';
                return;
              }
              qrcodeElement.appendChild(canvas);
            });
          } catch (error) {
            console.error("生成二维码失败:", error);
            const qrcodeElement = document.getElementById('qrcode');
            qrcodeElement.innerHTML = '<div style="width: 120px; height: 120px; border: 1px solid #ccc; display: flex; align-items: center; justify-content: center; font-size: 12px;">二维码生成失败</div>';
          }


    },
    // 确认发货操作
    handleConfirm(row) {
      this.$modal.confirm('确认要发货吗？').then(() => {
        confirmDelivery(row.id).then(response => {
          this.$modal.msgSuccess("发货确认成功");
          this.getList();
        }).catch(error => {
          console.error('确认发货失败:', error);
          this.$modal.msgError("确认发货失败");
        });
      }).catch(() => {});
    },






    // 选择采购订单
    handleSelectPurchaseOrder() {
      this.purchaseOrderDialogVisible = true;
    },
    // 选择箱码
    handleSelectBoxCodes() {
      this.boxCodeDialogVisible = true;
    },

    // 处理采购订单选择
    handlePurchaseOrderSelect(selectedRow) {
      this.form=selectedRow;
      console.log("选择订单详情"+this.form)
      this.form.poId = selectedRow.poId;
      this.purchaseOrderDialogVisible = false;

    },

    // 处理箱码选择
    handleBoxCodeSelect(selectedBoxCodes) {
      this.selectedBoxCodes = selectedBoxCodes;
      this.boxCodeDialogVisible = false;

      // 更新送货清单中的数量
      this.updateDeliveryItems();
    },

    // 移除箱码
    handleRemoveBoxCode(index) {
      this.selectedBoxCodes.splice(index, 1);
      this.updateDeliveryItems();
    },
    // 更新送货清单
    updateDeliveryItems() {
      // 按存货分组统计
      const itemMap = new Map();

      this.selectedBoxCodes.forEach(box => {
        const itemId = box.itemId;
        if (!itemMap.has(itemId)) {
          itemMap.set(itemId, {
            poId: box.poId,
            itemId: itemId,
            poNum: this.form.poNum,
            codeNum: this.form.codeNum,
            itemName: box.itemName,
            spec: box.spec,
            uom: box.uom,
            currentDeliveryQuantity: 0,
            boxCount: 0,
            remark: ''
          });
        }

        const item = itemMap.get(itemId);
        item.currentDeliveryQuantity += box.boxNum;
        item.boxCount += 1;
      });
      this.deliveryItems = Array.from(itemMap.values());
    },

    // 查看按钮操作
    handleView(row) {
      this.loading = true;
      getDeliveryVO(row.id).then(response => {
        this.currentDelivery = response.data;
        this.viewOpen = true;
        this.loading = false;
      });
    },


    /** 查询发货单列表 */
    getList() {
      this.loading = true
      listDeliveryVO(this.queryParams).then(response => {
        this.deliveryList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deliveryId: null,
        poId: null,
        deliveryDate: null,
        deliveryStatus: null,
        totalBoxes: null,
        totalQuantity: null,
        remark: null,
        createdPerson: null,
        createdAt: null,
        updatedAt: null
      }
      this.deliveryDetailList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加发货单"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.ids= row.id;
      getDeliveryVO(id).then(response => {
        console.log(response.data);
        this.form = response.data;
        this.deliveryItems=response.data.deliveryItems;
        this.selectedBoxCodes=response.data.boxCodes;
        this.open = true
        this.title = "修改发货单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          if (this.selectedBoxCodes.length === 0) {
            this.$modal.msgError("请至少选择一个箱码");
            return;
          }

          this.loading = true;
          const deliveryVO = {
            ...this.form,
            deliveryItems: this.deliveryItems,
            boxCodes: this.selectedBoxCodes,
            totalBoxes: this.selectedBoxCodes.length,
            totalQuantity: this.selectedBoxCodes.reduce((total, box) => total + (box.boxNum || 0), 0),
            poNum : this.form.poNum,
            notcodeNum : this.form.notcodeNum,
          };



          if (this.form.id == null) {
            updateDelivery(deliveryVO).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addDelivery(deliveryVO).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除发货单编号为"' + ids + '"的数据项？').then(function() {
        return delDelivery(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 发货单明细序号 */
    rowDeliveryDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 发货单明细添加按钮操作 */
    handleAddDeliveryDetail() {
      let obj = {}
      obj.boxId = ""
      obj.createdAt = ""
      obj.updatedAt = ""
      this.deliveryDetailList.push(obj)
    },
    /** 发货单明细删除按钮操作 */
    handleDeleteDeliveryDetail() {
      if (this.checkedDeliveryDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的发货单明细数据")
      } else {
        const deliveryDetailList = this.deliveryDetailList
        const checkedDeliveryDetail = this.checkedDeliveryDetail
        this.deliveryDetailList = deliveryDetailList.filter(function(item) {
          return checkedDeliveryDetail.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleDeliveryDetailSelectionChange(selection) {
      this.checkedDeliveryDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/delivery/export', {
        ...this.queryParams
      }, `delivery_${new Date().getTime()}.xlsx`)
    },
  }
}
</script>
<style scoped>
/* 打印样式 */
@media print {
  body * {
    visibility: hidden;
  }
  #printContent, #printContent * {
    visibility: visible;
  }
  /* 确保打印内容占据整个页面 */
  #printContent {
    position: fixed !important;
    left: 0 !important;
    top: 0 !important;
    width: 100% !important;
    height: 100% !important;
    background: white !important;
    margin: 0 !important;
    padding: 0 !important;
    z-index: 99999 !important;
    overflow: visible !important;
  }
  .print-container {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
  }
  /* 隐藏不需要打印的元素 */
  .no-print {
    display: none !important;
  }
  /* 隐藏所有页面元素 */
  body, .app-wrapper, .navbar, .sidebar-container, .main-container, .app-main, .tags-view, .el-header, .el-aside, .el-main {
    visibility: hidden !important;
    display: none !important;
  }

  /* 只显示打印内容 */
  #printContent, #printContent * {
    visibility: visible !important;
  }
  /* 确保在屏幕上查看时打印内容不显示 */
  @media screen {
    #printContent {
      display: none !important;
    }
  }


}
</style>
